package org.su.generalmvc.scheduler;

import org.su.generalmvc.core.LifeCycle;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SecondSchedulerTask extends SchedulerTask {
	// 线程中断标志
	protected volatile boolean done = false;
	// 定时器间隔时间 > 0 and < 60
	private int millis = 30 * 1000;

	public SecondSchedulerTask(Object controller, Method method, int seconds) {
		super(controller, method);

		if (seconds > 0 && seconds < 60) {
			this.millis = seconds * 1000;
		}
	}

	@Override
	public void run() {
		try {
			long firstTime = System.currentTimeMillis();
			long endTime = firstTime;

			synchronized (this) {
				while (!done) {
					LifeCycle.invoke(controller, method, transLevel);
					endTime = System.currentTimeMillis();

					long diffTime = (endTime - firstTime);
					if (diffTime + millis >= 60 * 1000)
						break;
					
					this.wait(millis - (diffTime % millis));
				}
			}
		} catch(InterruptedException e) {
			// NOOP: 线程中断
		} catch(InvocationTargetException e) {
			if (e.getCause() != null) {
				logger.error(e.getCause().getMessage(), e.getCause());
			} else {
				logger.error(e.getMessage(), e);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	@Override
	public void cancel() {
		done = true;
		this.notifyAll();
	}
}
